package com.wf.smartcomm.server.serviceImpl;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.wf.smartcomm.server.bean.Merchant;
import com.wf.smartcomm.server.bean.MerchantUser;
import com.wf.smartcomm.server.model.Page;
import com.wf.smartcomm.server.service.MerchantUserService;

@Service
@Transactional
public class MerchantUserServiceImpl implements MerchantUserService {
	
	@Resource
	private SessionFactory sessionFactory;

	@Override
	public void save(MerchantUser merchantUser) throws Exception {
		sessionFactory.getCurrentSession().persist(merchantUser);
	}

	@Override
	public void update(MerchantUser merchantUser) throws Exception {
		sessionFactory.getCurrentSession().merge(merchantUser);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public MerchantUser get(String id) throws Exception {
		return (MerchantUser) sessionFactory.getCurrentSession().get(MerchantUser.class, id);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public MerchantUser login(String username, String password) throws Exception {
		Query query = sessionFactory.getCurrentSession().createQuery("from MerchantUser where username = binary(:username) and password = binary(:password)");
		query.setParameter("username", username);
		query.setParameter("password", password);
		return (MerchantUser) query.uniqueResult();
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public void list(Page page) throws Exception {
		Query query = sessionFactory.getCurrentSession().createSQLQuery("select count(*) from MerchantUser");
		Long counts = (Long) query.uniqueResult();
		page.setTotalCount(counts.intValue());
		query = sessionFactory.getCurrentSession().createQuery("from MerchantUser order by createdAt desc");
		query.setMaxResults(page.getPageSize());
		query.setFirstResult(page.getBeginIndex());
		page.setDataList(query.list());
	}

	@Override
	public MerchantUser getByUsername(String username) throws Exception {
		Query query = sessionFactory.getCurrentSession().createQuery("from MerchantUser where username = :username");
		query.setParameter("username", username);
		return (MerchantUser) query.uniqueResult();
	}

	@Override
	public MerchantUser get(Merchant merchant) throws Exception {
		Query query = sessionFactory.getCurrentSession().createQuery("from MerchantUser where merchant = :merchant");
		query.setParameter("merchant", merchant);
		return (MerchantUser) query.uniqueResult();
	}

}
